import BScroll from 'better-scroll'; 
import useExpose from '../../hook/useExpose'
import { useOtherListener } from '../../hook/useEventListener'
import { debounce } from '../../utils/'
import { defineComponent, nextTick, onBeforeUnmount, onMounted, reactive, ref } from "vue";
import './style.scss'

export default defineComponent({
  name: 'Scroll',
  props: {
    scrollY: {
      type: Boolean,
      default: false
    },
    scrollX: {
      type: Boolean,
      default: false
    },
    height: {
      type: String,
      default: '100%'
    },
    trigger: {
      type: Function,
      default: () => {}
    },
    onScroll: {
      type: Function
    },
    pullDown: {
      type: Boolean,
      default: false
    },
    handlePullUp: {
      type: Function
    }
  },
  setup(props, { slots, emit }) {
    const state = reactive({
      scroll: null
    })

    const containerRef = ref(null)

    const refresh = () => {
      nextTick(() => {
        state.scroll.refresh()
      })
    }

    const bindScroll = () => {
      if (state.scroll && props.onScroll) {
        state.scroll.on('scroll', props.onScroll)
      }
    }

    onBeforeUnmount(() => {
      state.scroll.off('scroll', props.onScroll)
    })

    onMounted(() => {
      const scroll = state.scroll = new BScroll(containerRef.value, {
        scrollX: !!props.scrollX,
        scrollY: !!props.scrollY,
        probeType: 3,
        click: true
      })

      if (props.pullDown) {
        const handlePullUp = () => {
          //判断是否滑动到了底部
          if(scroll.y === scroll.maxScrollY) {
            props.handlePullUp()
          }
        };
  
        useOtherListener(scroll, 'scrollEnd', handlePullUp)
      }
      bindScroll()
      refresh()
    })

    // 暴露
    useExpose({
      refresh,
      containerRef
    })

    return () => (
      <div className={[!props.scrollX ? 'container-box' : null]} style={{ height: props.scrollX ? 'auto' : props.height }} ref={containerRef}>
        <div className="scroll-wrapper">
          { slots }
        </div>
      </div>
    )
  }
})